package searchtab.util;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IFindReplaceTarget;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

import searchtab.SearchTabActivator;

public class SearchTabUtils {

    public static ITextEditor getEditor() {
        IWorkbenchPage page = getWorkbenchWindow();
        ITextEditor editor = null;
        if (page != null && page.getActiveEditor() != null) {
            IEditorPart part = page.getActiveEditor();
            // if (part instanceof MultiPageEditorPart) {
            // MultiPageEditorPart selectedPage = (MultiPageEditorPart) part;
            // if (selectedPage.getSelectedPage() instanceof ITextEditor) {
            // return (ITextEditor) selectedPage.getSelectedPage();
            // }
            //
            // }
            if (part instanceof ITextEditor) {
                editor = (ITextEditor) part;
            }
            Object adapter = part.getAdapter(ITextEditor.class);
            if (adapter instanceof ITextEditor) {
                return (ITextEditor) adapter;
            }
        }
        return editor;
    }

    public static IWorkbenchPage getWorkbenchWindow() {
        return SearchTabActivator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
    }

    public static IFindReplaceTarget getFindReplaceTarget() {
        IWorkbenchPart part = SearchTabUtils.getEditor();
        IFindReplaceTarget target = null;
        target = part == null ? null : (IFindReplaceTarget) part.getAdapter(IFindReplaceTarget.class);

        return target;

    }

    public static IDocument getDocument() {

        ITextEditor editor = SearchTabUtils.getEditor();
        if (editor == null) {
            return null;
        }

        IDocumentProvider documentProvider = editor.getDocumentProvider();

        return documentProvider.getDocument(editor.getEditorInput());
    }

}
